<template>
  <a-layout>
    <a-layout-content class="main-layout-content">
      <a-card class="search-card">
        <!-- 搜索栏 -->
        <a-row>
          <a-col :span="15">
            <a-form-model-item :labelCol="{ span: 4, offset: 1 }" :wrapperCol="{ span: 14, offset: 1 }" label="系统名称：">
              <a-input :value="systemName" v-model="searchKey" @pressEnter="search" />
            </a-form-model-item>
          </a-col>
          <a-col :span="5">
            <a-form-model-item>
              <a-button type="primary" class="search-button" @click="search">搜索</a-button>
              <a-button type="primary" class="reset-button" @click="reset">重置</a-button>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-button type="primary" class="add-button" @click="showModal()">
            添加
          </a-button>
        </a-row>
        <!-- 表格 -->
        <a-row>
          <a-table :columns="columns" :data-source="systemArray" :loading="loading" bordered
            :row-key="(record, index) => index + 1" :pagination="pagination" @change="handleTableChange">
            <template v-for="col in ['name']" :slot="col" slot-scope="text, record, index">
              <div>
                <a-input v-if="record.editing" class="systemName-input" :value="text"
                  @change="e => handleChange(e.target.value, record.id, col)" />
                <template v-else>
                  {{ text }}
                </template>
              </div>
            </template>
            <template slot="operation" slot-scope="text, record, index">
              <div class="editable-row-operations">
                <span v-if="record.editing">
                  <a @click="() => save(text, record, index)">确定</a>
                  <a-popconfirm title="是否确定取消?" ok-text="确定" cancel-text="取消" @confirm="() => cancel(record.id)">
                    <a>取消</a>
                  </a-popconfirm>
                </span>
                <span v-else>
                  <a :disabled="editingId !== ''" @click="() => edit(record.id)">编辑</a>
                  <a-popconfirm v-if="systemArray.length" title="确定删除?" ok-text="确定" cancel-text="取消"
                    @confirm="() => delete_(record.id)">
                    <a href="javascript:;">删除</a>
                  </a-popconfirm>
                  <a :disabled="editingId !== ''" @click="() => openDetail(record)">详细</a>
                </span>
              </div>
            </template>
          </a-table>
          <template slot="name" slot-scope="name"> {{ name.first }} {{ name.last }} </template>
        </a-row>
      </a-card>
    </a-layout-content>
    <a-drawer width="300" placement="right" :closable="false" :visible="detailVisibale" @close="closeDetail()">
      <p class="drawer-title">
        详细信息
        <a-row type="flex">
          <a-col flex="100px">名称：</a-col>
          <a-col flex="auto">{{ systemNameInDetail }}</a-col>
        </a-row>
      </p>
    </a-drawer>
    <!-- 对话框-添加系统 -->
    <a-modal :visible="modalVisible" title="添加系统" okText='确认' cancel-text="取消" @cancel="handleModalCancel"
      @ok="handleModalOk">
      <!--表单 并将表单的值绑定到this.from-->
      <a-form layout='vertical' :form="form">
        <a-form-item label='系统名称' :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }">
          <a-input class="add-input" v-decorator="[
            'systemName',
            {
              rules: [{ required: true, message: '请填写系统名称!' }],
            }
          ]" @pressEnter="handleModalOk" />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-layout>
</template>
<script>
import { columns } from '@/views/configuration/system/data/configData.js';
import { page, add, deleteById, updateById } from '@/api/configuration/systemApi.js';
export default {
  //el 创建前
  beforeCreate() {
    //创建表单
    this.form = this.$form.createForm(this, { name: 'formInModal' });
  },
  data() {
    return {
      /**
       * 系统名称
       */
      systemName: '',
      /**
       * 搜索栏中的关键字
       */
      searchKey: '',
      /**
       * 表格的数据
       */
      systemArray: [],
      /**
       * 分页对象
       */
      pagination: {
        /**
         * 当前页码
         */
        current: 1,
        /**
         * 当前页码
         */
        pageSize: 5,
        /**
         * 总条数，后端返回
         */
        total: 0,
        /**
         * 分页右下角显示信息
         */
        showTotal: (total, range) => `${range[0]}-${range[1]} 条，总共 ${total} 条`,
        /**
         * 是否可改变每页显示条数
         */
        showSizeChanger: true,
        /**
         * 可选的每页显示条数
         */
        pageSizeOptions: ['5', '10', '20', '50', '100'],
      },
      /**
       * 表格是否处于更新状态
       */
      loading: false,
      /**
       * 表格的列
       */
      columns,
      /**
       * 当前正在编辑的这条记录的id，如果为空字符串则表示此时没有记录处于被编辑状态
       */
      editingId: '',
      /**
       * 详细信息是否可见
       */
      detailVisibale: false,
      /**
       * 系统名称，在详细信息弹出框中
       */
      systemNameInDetail: '',
      /**
       * 添加系统对话框是否显示
       */
      modalVisible: false,
    };
  },
  created() {
    console.debug(`created函数被调用`);
  },
  mounted() {
    console.debug(`mounted函数被调用`);
    // 组件挂载后获取第一页数据
    this.pageSystem(this.pagination.current, this.pagination.pageSize, '');
  },
  methods: {
    /**
     * 搜索按钮
     */
    search() {
      console.debug(`搜索内容为：${this.searchKey}`);
      this.pageSystem(this.pagination.current, this.pagination.pageSize, '');
      
      // page({ pageNo: this.pagination.current, pageSize: this.pagination.pageSize, Name: this.searchKey }).then(res => {
      //   debugger;
      //   if (res.Success) {
      //     this.pagination.total = res.Result.Total;
      //     this.systemArray = res.Result.List;
      //   } else {
      //     console.warn(`接口调用失败`);
      //   }
      //   this.loading = false;
      // });
    },
    /**
     * 重置按钮
     */
    reset() {
      console.debug(`搜索内容被重置`);
      this.searchKey = '';
    },
    /**
     * 名称列内容变化时，将新的名称显示在表格中
     * @param {*} value 
     * @param {*} id 
     * @param {*} column 
     */
    handleChange(value, id, column) {
      const newData = [...this.systemArray];
      const target = newData.find(item => id === item.id);
      if (target) {
        target[column] = value;
        this.systemArray = newData;
      }
    },
    /**
     * 分页显示表格
     */
    pageSystem(pageNo, pageSize, name) {
      console.debug(`分页显示表格`);
      this.loading = true;
      page({ pageNo, pageSize, name }).then(res => {
        if (res.Success) {
          this.pagination.total = res.Result.Total;
          this.systemArray = res.Result.List;
        } else {
          console.warn(`接口调用失败`);
        }
        this.loading = false;
      });
    },
    /**
     * 表格分页、排序、筛选等事件的处理函数
     * @param {*} pagination 
     * @param {*} filters 
     * @param {*} sorter 
     */
    handleTableChange(pagination, filters, sorter) {
      // 更新分页对象
      this.pagination = pagination;
      // 发起数据请求，获取对应页码的数据
      this.pageSystem(this.pagination.current, this.pagination.pageSize, '');
    },
    /**
     * 编辑按钮，将这条记录的editing属性设置为true，并且更新this.systemArray
     * @param {*} id 
     */
    edit(id) {
      const newData = [...this.systemArray];
      const target = newData.find(item => id === item.id);
      this.editingId = id;
      if (target) {
        target.editing = true;
        this.systemArray = newData;
      }
    },
    /**
     * 编辑按钮-->确定按钮。更新表格，调用接口修改记录
     */
    save(text, record, index) {
      const newData = [...this.systemArray];
      const target = newData.find(item => record.id === item.id);
      if (target) {
        delete target.editing;
        this.systemArray = newData;

        // 调用接口修改记录
        updateById({ id: record.id, name: record.name }).then(res => {
          if (res.Success) {
            this.pageSystem(this.pagination.current, this.pagination.pageSize, '');
          } else {
            console.warn(`接口调用失败`);
          }
          this.loading = false;
        });
      }
      this.editingId = '';
    },
    /**
     * 弹出框的确定按钮
     * @param {*} id 
     */
    cancel(id) {
      const newData = [...this.systemArray];
      const target = newData.find(item => id === item.id);
      this.editingId = '';
      if (target) {
        delete target.editing;
        this.systemArray = newData;
      }
    },
    /**
     * 点击删除按钮，删除一条记录
     * @param {*} id 
     */
    delete_(id) {
      this.loading = true;
      deleteById(id).then(res => {
        if (res.Success) {
          this.pageSystem(this.pagination.pageNo, this.pagination.pageSize);
          if (this.pagination.total % this.pagination.pageSize == 0) {
            this.pagination.current = this.pagination.current - 1;
          }
        } else {
          console.warn(`接口调用失败`);
        }
        this.loading = false;
      });
    },
    /**
     * 打开详细信息弹窗
     */
    openDetail(record) {
      this.detailVisibale = true;
      this.systemNameInDetail = record.name;
    },
    /**
     * 关闭详细信息弹窗
     */
    closeDetail() {
      this.detailVisibale = false;
    },
    /**
     * 显示添加系统对话框
     */
    showModal() {
      // 收回之前的错误提示
      this.form.resetFields();
      this.modalVisible = true;
    },
    /**
     * 关闭添加系统对话框
     */
    handleModalCancel(e) {
      this.form.resetFields();
      this.modalVisible = false;
    },
    /**
     * 点击添加系统对话框上的确认按钮
     */
    handleModalOk(e) {
      const form = this.form;
      form.validateFields((err, value) => {
        if (err) {
          return;
        }

        console.debug(`添加的系统的名称: ${value.systemName}`);

        // 添加系统
        add({ Name: value.systemName }).then(res => {
          if (res.Success) {
            this.pageSystem(this.pagination.current, this.pagination.pageSize);
            form.resetFields();
          this.modalVisible = false;
          } else {
            console.warn(`接口调用失败：${res.Message}`);
            this.$message.warning(`${res.Message}`);
          }
        });
      });
    },
  },
};
</script>
<style scoped>
</style>
